package com.luoran.system.utils;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class MinioUpload {


    /**
     * 上传图片
     * @param file
     * @return
     */
    public static String uploadPic(MultipartFile file){

        // todo  这三个参数改成自己的
        String bucketName = "test";
        String accessKey = "APaMsQWeV1d7LP3Y";
        String secretKey = "wvVMSrD9JpKs06iPswsI8i6g3rSNRJwt";

        MinioClient minioClient = MinioClient.builder()
                .endpoint("http://127.0.0.1:9000")
                .credentials(accessKey, secretKey)
                .build();

        String requestBodyContent = "some content";
        MediaType mediaType = MediaType.get("application/json");
        RequestBody requestBody = RequestBody.create(mediaType, requestBodyContent);
// 然后将requestBody添加到请求中
        Request request = new Request.Builder()
                .url("https://example.com/api")
                .post(requestBody)
                .build();

        // 新的文件名
        String filename = UUID.randomUUID() + file.getOriginalFilename();

        try {
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(filename).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
        } catch (ErrorResponseException e) {
            throw new RuntimeException(e);
        } catch (InsufficientDataException e) {
            throw new RuntimeException(e);
        } catch (InternalException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (InvalidResponseException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (ServerException e) {
            throw new RuntimeException(e);
        } catch (XmlParserException e) {
            throw new RuntimeException(e);
        }


        return "http://127.0.0.1:9000/" + bucketName + "/" + filename;
    }
}
